<template>
  <div id="addQuestionView">
    <h2>创建题目</h2>
    <a-form :model="form" label-align="left">
      <a-form-item field="title" label="标题">
        <a-input v-model="form.title" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item field="tags" label="标签">
        <!-- 替换为多选下拉框 -->
        <a-select
          v-model="form.tags"
          placeholder="请选择或输入标签"
          :options="availableTags"
          multiple
          allow-create
          filterable
          @change="handleTagChange"
          :style="{ width: '100%' }"
        />
      </a-form-item>
      <a-form-item field="content" label="题目内容">
        <MdEditor
          :value="form.content"
          :handle-change="onContentChange"
          :delay="300"
        />
      </a-form-item>
      <a-form-item field="answer" label="答案">
        <MdEditor
          :value="form.answer"
          :handle-change="onAnswerChange"
          :delay="300"
        />
      </a-form-item>
      <a-form-item label="判题配置" :content-flex="false" :merge-props="false">
        <a-space direction="vertical" style="min-width: 480px">
          <a-form-item field="judgeConfig.timeLimit" label="时间限制">
            <a-input-number
              v-model="form.judgeConfig.timeLimit"
              placeholder="请输入时间限制"
              mode="button"
              min="0"
              size="large"
            />
          </a-form-item>
          <a-form-item field="judgeConfig.memoryLimit" label="内存限制">
            <a-input-number
              v-model="form.judgeConfig.memoryLimit"
              placeholder="请输入内存限制"
              mode="button"
              min="0"
              size="large"
            />
          </a-form-item>
          <a-form-item field="judgeConfig.stackLimit" label="堆栈限制">
            <a-input-number
              v-model="form.judgeConfig.stackLimit"
              placeholder="请输入堆栈限制"
              mode="button"
              min="0"
              size="large"
            />
          </a-form-item>
        </a-space>
      </a-form-item>
      <a-form-item
        label="测试用例配置"
        :content-flex="false"
        :merge-props="false"
      >
        <a-form-item
          v-for="(judgeCaseItem, index) of form.judgeCase"
          :key="index"
          no-style
        >
          <a-space direction="vertical" style="min-width: 640px">
            <a-form-item
              :field="`form.judgeCase[${index}].input`"
              :label="`输入用例-${index + 1}`"
              :key="index"
            >
              <a-input
                v-model="judgeCaseItem.input"
                placeholder="请输入测试输入用例"
              />
            </a-form-item>
            <a-form-item
              :field="`form.judgeCase[${index}].output`"
              :label="`输出用例-${index + 1}`"
              :key="index"
            >
              <a-input
                v-model="judgeCaseItem.output"
                placeholder="请输入测试输出用例"
              />
            </a-form-item>
            <a-button status="danger" @click="handleDelete(index)">
              删除
            </a-button>
          </a-space>
        </a-form-item>
        <div style="margin-top: 32px">
          <a-button @click="handleAdd" type="outline" status="success">
            新增测试用例
          </a-button>
        </div>
      </a-form-item>
      <div style="margin-top: 16px" />
      <a-form-item>
        <a-button type="primary" style="min-width: 200px" @click="doSubmit">
          提交
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import MdEditor from '@/components/MdEditor.vue'
import { QuestionControllerService } from '../../../generated'
import message from '@arco-design/web-vue/es/message'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
// 如果页面地址包含 update，视为更新页面
const updatePage = route.path.includes('update')

// 可用的标签列表
const availableTags = ref([
  '简单',
  '中等',
  '困难',
  '数组',
  '字符串',
  '哈希表',
  '动态规划',
  '数学',
  '排序',
  '贪心',
  '深度优先搜索',
  '数据库',
  '二叉树',
  '二分查找',
  '树',
  '矩阵',
  '栈',
  '堆',
  '设计',
  '图',
  '模拟',
  '回溯',
  '链表',
  '双指针',
  '位运算',
  '广度优先搜索',
  '并查集',
  '递归',
  '滑动窗口',
  '前缀和',
  '队列',
  '枚举',
  '哈希'
])

const form = ref({
  title: '',
  tags: [],
  answer: '',
  content: '',
  judgeConfig: {
    memoryLimit: 1000,
    stackLimit: 1000,
    timeLimit: 1000
  },
  judgeCase: [
    {
      input: '',
      output: ''
    }
  ]
})

/**
 * 根据题目 id 获取老的数据
 */
const loadData = async () => {
  const id = route.query.id
  //不存在题目编号,不回显
  if (!id) {
    return
  }
  //向后端获取题目发送请求
  const res = await QuestionControllerService.getQuestionByIdUsingGet(id as any)
  if (res.code === 0) {
    form.value = res.data as any

    // 处理判题配置
    if (!form.value.judgeConfig) {
      form.value.judgeConfig = {
        memoryLimit: 1000,
        stackLimit: 1000,
        timeLimit: 1000
      }
    } else {
      //之所以没有回显是因为数据类型不匹配问题,已解决
      form.value.judgeConfig = {
        timeLimit: Number(form.value.judgeConfig.timeLimit) || 1000,
        memoryLimit: Number(form.value.judgeConfig.memoryLimit) || 1000,
        stackLimit: Number(form.value.judgeConfig.stackLimit) || 1000
      }
    }

    // 处理测试用例
    if (!form.value.judgeCase || !Array.isArray(form.value.judgeCase)) {
      form.value.judgeCase = [
        {
          input: '',
          output: ''
        }
      ]
    }

    // 处理标签
    if (!form.value.tags) {
      form.value.tags = []
    }
  } else {
    message.error('加载失败，' + res.message)
  }
}

onMounted(() => {
  loadData()
})

const doSubmit = async () => {
  // 区分更新还是创建
  if (updatePage) {
    const res = await QuestionControllerService.updateQuestionUsingPost(
      form.value
    )
    if (res.code === 0) {
      message.success('更新成功')
      router.push({
        path: '/manage/question'
      })
    } else {
      message.error('更新失败，' + res.message)
    }
  } else {
    const res = await QuestionControllerService.addQuestionUsingPost(form.value)
    if (res.code === 0) {
      message.success('创建成功')
      router.push({
        path: '/manage/question'
      })
    } else {
      message.error('创建失败，' + res.message)
    }
  }
}

/**
 * 新增判题用例
 */
const handleAdd = () => {
  form.value.judgeCase.push({
    input: '',
    output: ''
  })
}

/**
 * 删除判题用例
 */
const handleDelete = (index: number) => {
  form.value.judgeCase.splice(index, 1)
}

const onContentChange = (value: string) => {
  form.value.content = value
}

const onAnswerChange = (value: string) => {
  form.value.answer = value
}

/**
 * 处理标签变化
 */
const handleTagChange = (value: string[]) => {
  // 当用户添加新标签时，将其添加到可用标签列表
  value.forEach((tag) => {
    if (!availableTags.value.includes(tag)) {
      availableTags.value.push(tag)
    }
  })
}
</script>

<style scoped>
#addQuestionView {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 24px;
  color: #1c1c1e;
  font-weight: 600;
}

.arco-form-item {
  margin-bottom: 20px;
}

.arco-select {
  border-radius: 6px;
  border: 1px solid #e4e6eb;
}

.arco-input-tag {
  border-radius: 6px;
  border: 1px solid #e4e6eb;
}

.arco-input-number {
  width: 100%;
}

.arco-btn {
  border-radius: 6px;
  font-weight: 500;
}

.arco-space-vertical > * {
  margin-bottom: 16px;
}
</style>
